//
//  HLHomeViewController.m
//  HLAerospace
//
//  Created by hulian-ios on 17/8/29.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//

#import "HLHomeViewController.h"
#import "WRNavigationBar.h"
#import "HLMenuButton.h"
#import "HLSearchViewController.h"
#import "MBProgressHUD+HL.h"
#import "HttpRequestManager.h"
#import <MJExtension/MJExtension.h>
#import <SDCycleScrollView/SDCycleScrollView.h>
#import "HLCourse.h"
#import "HLItemCourseView.h"
#import "HLSeeMoreViewController.h"
#import "HLCourseFoldViewController.h"
#import "HLMoreCourse.h"
#import "HLFoldCourse.h"
#import "HLCourseDetailViewController.h"
#import "HLArticleViewController.h"
#import "HLCourseFoldViewController.h"
#import "HLCategoryCourseController.h"
#import "HLDataBaseManager.h"
#import "HLSpaceSystermViewController.h"
#import "HLBanner.h"

#define kSDCycleScrollViewHeight (IS_IPHONE_5 ? 160 : 200)
#define kTableViewScetionViewHeight (IS_IPHONE_5 ? 34 : 40)

@interface HLHomeViewController () < SDCycleScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,HLItemCourseViewDelegate>

@property (nonatomic, strong) SDCycleScrollView *sd_scrollView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *searchButton;
@property (nonatomic ,strong) UIView *menuView;
@property (nonatomic ,strong) UIView *sectionHeadView;

/** 推荐视频数据源  */
@property (nonatomic ,strong) NSMutableArray *booksArrayList;
/** 热门课程数据源  */
@property (nonatomic ,strong) NSMutableArray *courseArrayList;
/**  temBanner*/
@property (nonatomic ,strong) NSMutableArray *temBanner;
/**  最新动态*/
@property (nonatomic ,strong) NSMutableArray *znewArraylist;
@end

@implementation HLHomeViewController

#pragma mark - Lazy

- (NSMutableArray *)booksArrayList
{
    if (!_booksArrayList) {
        _booksArrayList = [NSMutableArray array];
    }
    return _booksArrayList;
}

- (NSMutableArray *)courseArrayList
{
    if (!_courseArrayList) {
        _courseArrayList = [NSMutableArray array];
    }
    return _courseArrayList;
}
- (NSMutableArray *)temBanner
{
    if (!_temBanner) {
        _temBanner = [NSMutableArray array];
    }
    return _temBanner;
}

- (NSMutableArray *)znewArraylist
{
    if (!_znewArraylist) {
        _znewArraylist = [NSMutableArray array];
    }
    return _znewArraylist;
}


- (UIView*)menuView
{
    if (!_menuView) {
        _menuView = [[UIView alloc] init];
        [_menuView addSubview:self.sd_scrollView];
        
        CGFloat buttonW = ScreenWidth * 0.25;
        CGFloat buttonH = ScreenWidth * 0.3;
        for (int i = 0; i< [self meunImages].count; i++) {
            HLMenuButton *button = [HLMenuButton buttonWithType:UIButtonTypeCustom];
            button.tag = i;
            button.frame = CGRectMake((i % 4) *buttonW , ( i / 4) * buttonH + kSDCycleScrollViewHeight , buttonW, buttonH);
            [button setImage:[UIImage imageNamed:[self meunImages][i]] forState:UIControlStateNormal];
            [button setTitle:[self meunTitles][i] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(menuButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            [_menuView addSubview:button];
        }
    }
    return _menuView;
}

- (SDCycleScrollView *)sd_scrollView
{
    if (_sd_scrollView == nil) {
        NSArray *localImages = @[@"lagou0", @"lagou1", @"lagou2", @"lagou3"];
        _sd_scrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, ScreenWidth, kSDCycleScrollViewHeight) imageNamesGroup:localImages];
        _sd_scrollView.pageDotColor = [UIColor grayColor];
        _sd_scrollView.autoScrollTimeInterval = 2;
        _sd_scrollView.delegate = self;
        _sd_scrollView.currentPageDotColor = [UIColor whiteColor];
        _sd_scrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    }
    return _sd_scrollView;
}

#pragma mark - UI

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setUI];
    
    [self loadDataSource];
    
    
    /**** 数据缓存 ****/
    [MBProgressHUD show];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUD];
        if (![[AFNetworkReachabilityManager sharedManager] isReachable]) {
            if ([HLDataBaseManager homeDataCourse:1].count > 0) {
                [self.booksArrayList addObjectsFromArray:[HLDataBaseManager homeDataCourse:1]];
            }
            if ([HLDataBaseManager homeDataCourse:2].count > 0) {
                [self.courseArrayList addObjectsFromArray:[HLDataBaseManager homeDataCourse:2]];
            }
            [self.tableView reloadData];
        }
    });
    
    
}

- (NSArray *)meunTitles
{
    return @[@"航天器\n系统",@"航天运输\n系统",@"航天测控\n系统",@"航天着陆\n场系统",@"空间武器\n系统",@"航天应用\n系统",@"航天发射\n系统",@"航天指挥\n系统"];
}

- (NSArray *)meunImages
{
    return @[@"hangtianqi",@"hangtianyunshu",@"hangtiancekong",@"hangtianzhuolu",@"kongjianwuqi",@"yingyong",@"fashechang",@"zhihuikongzhi"];
}

- (UIView *)createSectionHeadView:(NSString *)title
{
    UIView *headView = [UIView new];
    headView.backgroundColor = [UIColor whiteColor];
    headView.height = kTableViewScetionViewHeight;
    UIView *line = [UIView new];
    line.frame = CGRectMake(10, 0, ScreenWidth - 20, 1);
    line.backgroundColor = HLRGB(240, 240, 240);
    [headView addSubview:line];
    
    UILabel *titleL = [[UILabel alloc] init];
    titleL.frame = CGRectMake(10, 1, ScreenWidth * 0.4, kTableViewScetionViewHeight - 1);
    titleL.textColor = HLRGB(60, 60, 60);
    titleL.font = [UIFont systemFontOfSize:IS_IPHONE_5 ? 12: kMainTitleFontSize];
    titleL.text = title;
    [headView addSubview:titleL];
    
    UIButton *moreb = [[UIButton alloc] init];
    moreb.frame = CGRectMake(ScreenWidth *0.6 - 10, 1, ScreenWidth * 0.4, kTableViewScetionViewHeight - 1);
    moreb.titleLabel.font = [UIFont systemFontOfSize:IS_IPHONE_5 ? 11: 14];
    [moreb setTitle:@"查看更多" forState:UIControlStateNormal];
    [moreb setTitleColor:HLRGB(120, 120, 120) forState:UIControlStateNormal];
       [headView addSubview:moreb];
    [moreb addTarget:self action:@selector(moreCourseClick:) forControlEvents:UIControlEventTouchUpInside];
    CGSize moreText = [moreb.titleLabel.text sizeWithAttributes:@{ NSFontAttributeName : moreb.titleLabel.font }];
    moreb.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -(ScreenWidth * 0.3 - (moreText.width * 0.5)));
    return headView;
}

- (void)setUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupNavItems];
    [self wr_setNavBarBarTintColor:kColorNavBG];
    [self wr_setNavBarBackgroundAlpha:0];
    
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    self.menuView.height = kSDCycleScrollViewHeight + ScreenWidth * 0.6;
    _tableView.tableHeaderView = self.menuView;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
}

- (void)setupNavItems
{
    self.searchButton = [[UIButton alloc]initWithFrame:CGRectMake(0, -3, 230, 30)];
    _searchButton.titleLabel.font = [UIFont systemFontOfSize:13];
    _searchButton.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    _searchButton.layer.cornerRadius = 15;
    _searchButton.backgroundColor = HLRGB(166, 166, 166);
    [_searchButton setTitle:@"搜索航天知识课程" forState:UIControlStateNormal];
    [_searchButton setTitleColor:HLRGB(20, 20, 20) forState:UIControlStateNormal];
    [_searchButton setImage:[UIImage imageNamed:@"搜索按钮"] forState:UIControlStateNormal];
    [_searchButton addTarget:self action:@selector(onClickSearchBtn) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = _searchButton;
}

#pragma mark - Request

- (void)loadDataSource
{
//    [MBProgressHUD show];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestHomedata signStr];
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestHomedata parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject) {
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 200) {
            [HLDataBaseManager removeALLHomeDatas];
//            weakSelf.booksArrayList = [HLCourse mj_objectArrayWithKeyValuesArray:responseObject[@"books"]];
            weakSelf.courseArrayList = [HLCourse mj_objectArrayWithKeyValuesArray:responseObject[@"courses"]];
            [weakSelf.tableView reloadData];
            /**** 最新动态 ****/
             weakSelf.znewArraylist =  [HLCourse mj_objectArrayWithKeyValuesArray:responseObject[@"courses2"]];
            for (HLCourse *course in  weakSelf.booksArrayList ) {
                [HLDataBaseManager addHomeDataCourse:course type:1];
            }
            for (HLCourse *course in  weakSelf.courseArrayList ) {
                [HLDataBaseManager addHomeDataCourse:course type:2];
            }
            
            
            weakSelf.temBanner = [HLBanner mj_objectArrayWithKeyValuesArray:responseObject[@"pics"]];
            NSMutableArray *picArrays = [NSMutableArray array];
            for (HLBanner *banene in self.temBanner) {
                [picArrays addObject:banene.book_img];
            }
            weakSelf.sd_scrollView.imageURLStringsGroup = picArrays;
            
           
            
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
//        [MBProgressHUD hideHUD];
//        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
}

#pragma mark -SDCycleScrollViewDelegate
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    HLBanner *banner = self.temBanner[index];
    HLFoldCourse *foldCourse = [HLFoldCourse new];
    if ([banner.course_type integerValue] == 1 ) {
        foldCourse.wkid = [NSString stringWithFormat:@"%@",banner.course_id];
        HLArticleViewController *article = [HLArticleViewController new];
        article.history_record_pic_url = banner.book_img;
        article.foldCourse = foldCourse;
        
        [self.navigationController pushViewController:article animated:YES];
    }
    
    if ([banner.course_type integerValue ]== 0) {
        foldCourse.wkid = [NSString stringWithFormat:@"%@",banner.course_id];
        HLCourseDetailViewController *couseDetail = [HLCourseDetailViewController new];
        couseDetail.history_record_pic_url = banner.book_img;
        couseDetail.foldCourse = foldCourse;
        [self.navigationController pushViewController:couseDetail animated:YES];
    }
}


#pragma mark - Private

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY < 0) {
        [self updateNavBarButtonItemsAlphaAnimated:0.0f];
    }else {
        [self updateNavBarButtonItemsAlphaAnimated:1.0];
    }
    
    if (offsetY >  kSDCycleScrollViewHeight - 64 ){
        CGFloat alpha = (offsetY - 136) / kSDCycleScrollViewHeight;
        [self wr_setNavBarBackgroundAlpha:alpha > 1 ? 1 : alpha];
    }else{
        [self wr_setNavBarBackgroundAlpha:0];
    }
}

- (void)updateNavBarButtonItemsAlphaAnimated:(CGFloat)alpha
{
    [UIView animateWithDuration:0.2 animations:^{
        [self.navigationController.navigationBar wr_setBarButtonItemsAlpha:alpha hasSystemBackIndicator:NO];
    }];
}


#pragma mark - tableview delegate / dataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    CGFloat itemWH = (ScreenWidth - 25) * 0.5;
    /***** 不用来回移除View ****/
    if (indexPath.section == 0) {
        for (int i = 0; i < self.znewArraylist.count; i++){
            if(cell.contentView.subviews.count == self.znewArraylist.count){
                HLItemCourseView *itemView = cell.contentView.subviews[i];
                itemView.course = self.znewArraylist[i];
            }else{
                HLItemCourseView *itemView = [[HLItemCourseView alloc] initWithFrame: CGRectMake(10 + i % 2 * (itemWH + 5) , i / 2 *itemWH  , itemWH, itemWH)];
                itemView.delegate = self;
                [cell.contentView addSubview:itemView];
                itemView.course = self.znewArraylist[i];
                itemView.categaryTitle.hidden = NO;
            }
        }
    }
    /***** 避免重复添加 ****/
    if (indexPath.section == 1) {
        for (int i = 0; i < self.courseArrayList.count; i++) {
            if (cell.contentView.subviews.count == self.courseArrayList.count){
                HLItemCourseView *itemView = cell.contentView.subviews[i];
                itemView.course = self.courseArrayList[i];
            }else{
                HLItemCourseView *itemView = [[HLItemCourseView alloc] initWithFrame: CGRectMake(10 + i % 2 * (itemWH + 5) , i / 2 *itemWH  , itemWH, itemWH)];
                itemView.delegate = self;
                itemView.categaryTitle.hidden = NO;
                [cell.contentView addSubview:itemView];
                itemView.course = self.courseArrayList[i];;
               
            }
        }
    }
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return  2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat itemWH = ( ScreenWidth - 25) *0.5;
    NSInteger bCount = self.znewArraylist.count % 2 == 0 ?  (self.znewArraylist.count/2):(self.znewArraylist.count/2) + 1;
    NSInteger cCount = self.courseArrayList.count % 2 == 0 ?  (self.courseArrayList.count/2):(self.courseArrayList.count/2) + 1;
    return  indexPath.section == 0 ?  bCount* itemWH : cCount *itemWH;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
   
    return section == 0 ? [self createSectionHeadView:@"最新动态"] : [self createSectionHeadView:@"推荐视频"];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kTableViewScetionViewHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001f;
}

- (UIImage *)imageWithImageSimple:(UIImage *)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(CGSizeMake(newSize.width*2, newSize.height*2));
    [image drawInRect:CGRectMake (0, 0, newSize.width*2, newSize.height*2)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


#pragma mark - Control

/**** 查看更多 ***/
- (void)moreCourseClick:(UIButton *)btn
{
    CGPoint po =  [btn.superview convertPoint:btn.frame.origin toView:self.tableView];
    /**** 推荐视频的相对坐标 ****/
    if (po.y < kSDCycleScrollViewHeight + 0.6 * ScreenWidth + 10) {
        HLSeeMoreViewController *more = [[HLSeeMoreViewController alloc]init];
        more.type = HLSourceTypeVideo;
        [self.navigationController pushViewController:more animated:YES];
    }else{
        HLSeeMoreViewController *more = [[HLSeeMoreViewController alloc]init];
        more.type = HLSourceTypeCourse;
        [self.navigationController pushViewController:more animated:YES];
    }
}

- (void)menuButtonClick:(UIButton *)btn
{
    if (btn.tag == 0) {
        HLSpaceSystermViewController *sys = [HLSpaceSystermViewController new];
        [self.navigationController pushViewController:sys animated:YES];
        return;
    }
    
    HLCategoryCourseController *cate = [HLCategoryCourseController new];
    cate.index = btn.tag + 1;
    [self.navigationController pushViewController:cate animated:YES];
}

- (void)onClickLeft
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)onClickSearchBtn
{
    HLSearchViewController *search = [[HLSearchViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
}

#pragma mark - HLItemCourseViewDelegate
- (void)itemCourseView:(HLItemCourseView *)view itemDidClick:(HLCourse *)course
{
    if(course.book_id != 0){
        HLMoreCourse *more = [HLMoreCourse new];
        more.ID = [NSString stringWithFormat:@"%zd",course.book_id];
        more.name = course.book_name;
        more.pic = course.book_img;
        more.num =  course.num;
        HLCourseFoldViewController *fold = [HLCourseFoldViewController new];
        fold.course = more;
         [self.navigationController pushViewController:fold animated:YES];
        return;
    }
    
    HLFoldCourse *foldCourse = [HLFoldCourse new];
    if (course.course_type == 1 ) {
        foldCourse.wkid = [NSString stringWithFormat:@"%ld",course.course_id];
        HLArticleViewController *article = [HLArticleViewController new];
        article.history_record_pic_url = course.book_img;
        article.foldCourse = foldCourse;
        
        [self.navigationController pushViewController:article animated:YES];
    }
    
    if (course.course_type == 0) {
        foldCourse.wkid = [NSString stringWithFormat:@"%ld",course.course_id];
        HLCourseDetailViewController *couseDetail = [HLCourseDetailViewController new];
        couseDetail.history_record_pic_url = course.book_img;
        couseDetail.foldCourse = foldCourse;
        [self.navigationController pushViewController:couseDetail animated:YES];
    }
}

@end
